/**
 * 无限分类，前序遍历
 * 结构树图形
 *                          1 root 16
 * 
 *                2 A 9                  10 E 15
 * 
 *        3 B 6          7 D 8     11 F 12        13 G 14
 * 
 *  4 C 5
 * 
 * 
 * 查询 SELECT * FROM FoodTree WHERE Lft BETWEEN 2 AND 11;
 * 如果你给我一个节点的左和右值,我可以利用数学公式告诉你有多少子节点。
 * descendants = (right - left - 1) / 2 
 * 插入新节点,把父节点，右边值赋值给本次添加节点的左值，本次添加节点右值=左值+1，然后大于等于父亲节点右值的数据左值和右值分别+2，然后执行插入
 * UPDATE FoodTree SET Rgt = Rgt+2 WHERE Rgt => 6;
 * UPDATE FoodTree SET Lft = Lft+2 WHERE Lft => 6;
 * INSERT INTO FoodTree (Lft,Rgt,NodeName)values(6,7,'Strawberry');
 * 
 * 
 */

class BST{
    constructor(data) {
        this.data = data;
    }
    //子级树渲染
    find_child(pid) {
        let data = [];
        this.data.forEach((v,k) => {
            if (v.parentid == pid) {
                data.push({
                    id:v.id,
                    k:k
                });
            }
        });
        return data;
    }
    //生成树形图
    to_tree(pid = 0,left = 0, key = null){
        let right = left + 1;
        let childs = this.find_child(pid);
        // 对于父节点为0的进行循环，然后查出父节点为上面结果id的节点内容
        for (let index = 0; index < childs.length; index++) {
            let v = childs[index];
            right = this.to_tree(v.id,right,v.k);
        }
        if(key!= null && this.data[key] != undefined){
            //第一次进来
            this.data[key].left = left;
            this.data[key].right = right;
        }
        return right + 1;
    }
}
module.exports = BST;
